package tech.aistar.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 本类用来演示: 全局异常处理 - 监听整个项目中,如果出现了异常,都会进入到此处
 *
 * @author: success
 * @date: 2021/5/10 10:13 上午
 */
public class MyHandlerException implements HandlerExceptionResolver {

    /**
     * 有可能需要对已知异常和未知异常进行分别的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        System.out.println("全局异常处理器");
        ModelAndView modelAndView = new ModelAndView();
        if(e instanceof MyException){
            MyException e1 = (MyException) e;
            modelAndView.addObject("error",e.getMessage());
        }else{
            modelAndView.addObject("error","未知异常");
        }


        modelAndView.setViewName("error/error");
        return modelAndView;
    }
}
